#import threading
import urllib2, json
import os, sys

def readJson(filepath):
    with open(filepath, 'r') as f:
        d = json.load(f)
        f.close()
        return d

def saveJson(data, filepath):
    with open(filepath, 'w') as f:
        f.write(json.dumps(data))
        f.close()

def callJRpc(method, params):
    d = json.dumps({
        'jsonrpc': '2.0',
        'id': 'pi',
        'method': method,
        'params': params
    })
    c = urllib2.urlopen('http://192.168.3.19:6800/jsonrpc', d)
    return c

def addUris(downloads):
    for item in downloads:
        c = callJRpc('aria2.addUri', [[item]])
        if c != None:
            print(c.read())

def getSessions():
    c = callJRpc('aria2.tellActive', [['files']])
    if c != None:
        d = json.loads(c.read())
        if d.has_key('result'):
            return d['result']
    return None

def updateStatus():
    os.system('git pull origin master')
    
    jsonData = readJson('t.json')
    needReport = False

    if len(jsonData['downloads']) > 0:
        addUris(jsonData['downloads'])
        jsonData['downloads'] = []
        needReport = True

    #sessions = getSessions()
    #if sessions != None:
    #    jsonData['sessions'] = sessions
    #    saveJson(jsonData, 't.json')
    saveJson(jsonData, 't.json')

    if needReport:
        os.system('git add t.json && git commit -m "update status" && git push origin master')

#def timerCall():
#    updateStatus()
#    global timer
#    timer = threading.Timer(600, timerCall)
#    timer.start()

if __name__ == '__main__':
    #timerCall()
    updateStatus()

